package com.demo.webapp.kcfinder.result;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.demo.webapp.kcfinder.config.ResultConfig;
import com.demo.webapp.kcfinder.context.ActionContext;

/**
 * 页面结果调度类
 * 
 * @author ryuu.kk
 *
 */
public class ActionDispatcherResult implements Result {

	@Override
	public String render(ActionContext context, ResultConfig config)
			throws IOException, ServletException {
		
		String location = config.getResult();
		HttpServletRequest request = context.getRequest();
		HttpServletResponse response = context.getResponse();
		RequestDispatcher dispatcher = request.getRequestDispatcher(location);
		
		//分解配置参数
        if (context != null && location != null && location.length() > 0 && location.indexOf("?") > 0) {
        	String queryString = location.substring(location.indexOf("?") + 1);
        	Map<String, Object> map = context.getParameters();
        	Map<String, Object> queryMap = parseQueryString(queryString, context.getEncoding());
        	map.putAll(queryMap);
        }
        if (dispatcher == null) {
            response.sendError(404, "result '" + location + "' not found");
            return "404Error";
        }
        
		if (!response.isCommitted() && (request.getAttribute("javax.servlet.include.servlet_path") == null)) {

			dispatcher.forward(request, response);
        } else {
            dispatcher.include(request, response);
        }
		return null;
	}
	
	//参数分解
	private Map<String, Object> parseQueryString(String queryString, String encoding) {
		
		Map<String, Object> queryParams = new LinkedHashMap<String, Object>();
		if (queryString != null) {
			String[] params = queryString.split("&");
			for (int i = 0; i < params.length; i++) {
				if (params[i].trim().length() > 0) {
					String[] tmpParams = params[i].split("=");
					String paramName = null;
					String paramValue = "";
					if (tmpParams.length > 0) {
						paramName = tmpParams[0];
					}
					if (tmpParams.length > 1) {
						paramValue = tmpParams[1];
					}
					if (paramName != null) {
						try {
							paramName = URLDecoder.decode(paramName, encoding);
							paramValue = URLDecoder.decode(paramValue, encoding);
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}

						// 已存在Key,说明数组
						if (queryParams.containsKey(paramName)) {
							Object currentParam = queryParams.get(paramName);

							if (currentParam instanceof String) {
								queryParams.put(paramName, new String[] {(String) currentParam, paramValue });
							} else {
								String currentParamValues[] = (String[]) currentParam;
								if (currentParamValues != null) {
									List<String> paramList = new ArrayList<String>(Arrays.asList(currentParamValues));
									paramList.add(paramValue);
									String newParamValues[] = new String[paramList.size()];
									queryParams.put(paramName, paramList.toArray(newParamValues));
								} else {
									queryParams.put(paramName, new String[] { paramValue });
								}
							}
						} else {
							queryParams.put(paramName, paramValue);
						}
					}
				}
			}
		}
		return queryParams;
	}
}
